package service

import (
	repo "go-admin1/admin/system/dao"
	"go-admin1/admin/system/model"
	"strings"
)

// PermissionService 服务接口
type PermissionService interface {
	GetRolePermission(*model.User) map[string]struct{}
	GetMenuPermission(user *model.User) map[string]struct{}
}

type permissionService struct {
	roleDao repo.SysRoleDao
	menuDao repo.SysMenuDao
}

func (p permissionService) GetRolePermission(user *model.User) map[string]struct{} {
	roles := make(map[string]struct{})

	if 1 == user.ID {
		roles["admin"] = struct{}{}
	} else {
		perms := p.roleDao.GetByUserID(int64(user.ID))

		for _, perm := range perms {
			if perm != nil {
				roleKeys := strings.Split(strings.TrimSpace(perm.RoleKey), ",")
				for _, roleKey := range roleKeys {
					roles[roleKey] = struct{}{}
				}
			}
		}

	}
	return roles
}

func (p permissionService) GetMenuPermission(user *model.User) map[string]struct{} {
	perms := make(map[string]struct{})
	if 1 == user.ID {
		perms["*:*:*"] = struct{}{}
	} else {
		roles := p.roleDao.GetByUserID(int64(user.ID))
		if roles != nil && len(roles) > 0 {
			for _, role := range roles {
				if role.Status == "0" && user.ID != 1 {
					rolePerms := p.menuDao.GetMenuPermsByRoleId(role.RoleID)
					for perm := range rolePerms {
						if perm != "" {
							permParts := strings.Split(strings.TrimSpace(perm), ",")
							for _, part := range permParts {
								if part != "" {
									perms[strings.TrimSpace(part)] = struct{}{}
								}
							}
						}

					}
				}
			}
		}
	}
	return perms
}

// NewSysConfigService 创建配置参数服务实例
func NewPermissionService() PermissionService {
	return &permissionService{
		roleDao: repo.NewSysRoleDao(),
		menuDao: repo.NewSysMenuDao(),
	}
}
